#####################################################################
#
#                          C++ Assistant
#
# 
# Author : Guillaume Delhumeau <guillaume.delhumeau@gmail.com>
# License : GNU General Public License 3
#
#####################################################################

import os
import re
import File
import string

def look_for_project(doc):
	uri = doc.get_uri()
	uri = uri.replace("file://", "")
	dir = os.path.dirname(uri)
	found = False
	expression = re.compile('(.*(\.cppassist-proj))+$')
	while found == False:
		files = os.listdir(dir)
		for f in files:
			if f <> "" and expression.match(f) <> None:
				filename = dir+os.sep+f
				filename = filename.replace(os.linesep, "")
				return Project(filename, "file://"+dir.replace(os.linesep,""))
		if found == False:
			## Are we at the root? 
			if string.count(dir, os.sep)==1:
				return None
			dir = os.path.realpath(dir + os.sep + os.pardir)		
	

class Project:
	
	def __init__(self):
		self._files = []
		
	def __init__(self, path, uri):
		fproj = open(path, "r")
		files = fproj.readlines()
		self._files = []
		for f in files:
			self._files.append(File.File(os.path.basename(f),f, uri+os.sep+f.replace(os.linesep,"")))
		fproj.close()
		self._files.sort(File.file_alpha_compare)	
	
	def add_file(self, f):
		self._files.add(f)
		
	def get_files_from_keywords(self, keywords):
		regexp = []
		for k in keywords:
			regexp.append(re.compile(".*("+k+")+.*", re.IGNORECASE))
			
		result = []
		for f in self._files:
			ok = True
			for r in regexp:
				if r.match(f.basename) == None:
					ok = False
			if ok==True:
				result.append(f)
		return result
		
	
		

